import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    cars: [], //购物车数据
    userinfo:  null, //用户数据
    total: 0, //选中商品总价
    pNum: 0, // 购物车商品数量
  },
  getters: {
    // 计算总数量和总价格
    goodsCP(state) {
      let allCount = 0;
      let allPrice = 0;

      state.cars.forEach((v) => {
        allCount += v.count;
        if (v.ischecked) {
          allPrice += v.count * v.price;
        }
      });

      return {
        allCount,
        allPrice,
      };
    },
    getUserinfo(state) {
      return state.userinfo;
    },
  },
  mutations: {
    // 定义用于更新数据的方法
    setUserInfo(state, user) {
      // sessionStorage中存储是防止router-view刷新浏览器时数据丢失
      // sessionStorage.setItem("userinfo", JSON.stringify(user));
      state.userinfo = user;
    },
    // 添加商品
    addGoods(state, goods) {
      const flag = state.cars.some((v) => {
        if (v.id == goods.id) {
          v.count += goods.count;
          return true;
        }
      });
      if (!flag) {
        state.cars.push(goods);
      }
    },
    // 删除商品
    removeGoods(state, goodsId) {
      const index = state.cars.findIndex((v) => v.id === goodsId);
      state.cars.splice(index, 1);
    },
    // 传入当前选中商品总价
    addTotal(state, total) {
      state.total = total;
    },
    //修改当前购物车商品数量
    updateProductNum(state, val) {
      state.pNum = val;
    },
  },
  actions: {},
  modules: {},
});
